<template>
  <Page>
    <div class="tenant-management">
      <!-- 搜索区域 -->
      <div class="search-section">
        <Space>
          <Button type="primary" @click="handleAdd">新增租户</Button>
          <Button @click="handleRefresh">刷新</Button>
        </Space>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <Table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          @change="handleTableChange"
        />
      </div>

      <!-- 表单弹窗 -->
      <Modal
        v-model:open="formVisible"
        :title="formTitle"
        width="800px"
        :footer="null"
      >
        <TenantForm
          v-if="formVisible"
          :mode="formMode"
          :data="currentRecord"
          @success="handleFormSuccess"
          @cancel="handleFormCancel"
        />
      </Modal>

      <!-- 详情弹窗 -->
      <Modal
        v-model:open="detailVisible"
        title="租户详情"
        width="800px"
        :footer="null"
      >
        <TenantDetail
          v-if="detailVisible"
          :data="currentRecord"
        />
      </Modal>
    </div>
  </Page>
</template>

<script setup lang="ts">
import { computed, h, onMounted, reactive, ref } from 'vue';

import { Page } from '@vben/common-ui';

import { Button, message, Modal, Space, Table, Tag } from 'ant-design-vue';

import { tenantApi, type TenantItem, type TenantListParams } from '#/api/tenant';

import TenantDetail from './components/TenantDetail.vue';
import TenantForm from './components/TenantForm.vue';

defineOptions({
  name: 'TenantManagement',
});

// 响应式数据
const loading = ref(false);
const dataSource = ref<TenantItem[]>([]);
const formVisible = ref(false);
const detailVisible = ref(false);
const formMode = ref<'create' | 'edit'>('create');
const currentRecord = ref<TenantItem | null>(null);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 表格列配置
const columns = [
  {
    title: '租户名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
    ellipsis: true,
  },
  {
    title: '租户代码',
    dataIndex: 'code',
    key: 'code',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'is_active',
    key: 'is_active',
    width: 100,
    align: 'center' as const,
    customRender: ({ record }: { record: TenantItem }) => {
      return h(
        Tag,
        {
          color: record.is_active ? 'green' : 'red',
        },
        () => (record.is_active ? '启用' : '禁用')
      );
    },
  },
  {
    title: '到期时间',
    dataIndex: 'expire_at',
    key: 'expire_at',
    width: 180,
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right' as const,
    customRender: ({ record }: { record: TenantItem }) => {
      return h(Space, {}, () => [
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            onClick: () => handleView(record),
          },
          () => '查看'
        ),
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            onClick: () => handleEdit(record),
          },
          () => '编辑'
        ),
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            danger: true,
            onClick: () => handleToggleStatus(record),
          },
          () => (record.is_active ? '禁用' : '启用')
        ),
      ]);
    },
  },
];

// 计算属性
const formTitle = computed(() => {
  return formMode.value === 'create' ? '新增租户' : '编辑租户';
});

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true;
    const params: TenantListParams = {
      page: pagination.current,
      size: pagination.pageSize,
    };
    
    const response = await tenantApi.getList(params);
    dataSource.value = response.items;
    pagination.total = response.total;
  } catch (error) {
    message.error('获取数据失败');
    console.error('获取租户列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 表格操作方法
const handleAdd = () => {
  formMode.value = 'create';
  currentRecord.value = null;
  formVisible.value = true;
};

const handleEdit = (record: TenantItem) => {
  formMode.value = 'edit';
  currentRecord.value = record;
  formVisible.value = true;
};

const handleView = (record: TenantItem) => {
  currentRecord.value = record;
  detailVisible.value = true;
};

const handleToggleStatus = async (record: TenantItem) => {
  try {
    await tenantApi.toggleStatus(record.id, !record.is_active);
    message.success('状态更新成功');
    fetchData();
  } catch (error) {
    message.error('状态更新失败');
    console.error('更新状态失败:', error);
  }
};

const handleRefresh = () => {
  fetchData();
};

const handleTableChange = (paginationInfo: any) => {
  pagination.current = paginationInfo.current;
  pagination.pageSize = paginationInfo.pageSize;
  fetchData();
};

// 表单操作
const handleFormSuccess = () => {
  formVisible.value = false;
  fetchData();
};

const handleFormCancel = () => {
  formVisible.value = false;
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.tenant-management {
  padding: 16px;
}

.search-section {
  margin-bottom: 16px;
}

.table-section {
  background: white;
  border-radius: 6px;
  padding: 16px;
}
</style>